package com.cxps.cloud.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串转换工具类
 *
 * @author YouCai.Liu
 * @since 2021/10/9
 * ...
 */
public class StringConvertUtil {

    public static void main(String[] args) {
        String productName = humpConversionUnderscore("productName");
        System.out.println(productName);

        String str = humpConversionUnderscore("helloWorldBeiJingHuanYingNi");
        System.out.println(str);
    }


    /**
     * 驼峰转下划线
     * eg：userName -> user_name
     *
     * @param oldString 需要转换的字符串
     * @return 转换后的字符串
     */
    public static String humpConversionUnderscore(String oldString) {
        if (oldString == null) {
            return null;
        }
        StringBuffer sbf = new StringBuffer(oldString);
        StringBuffer underline = humpConversionUnderscore(sbf);
        return underline.toString().toLowerCase();
    }

    /**
     * 驼峰转下划线
     *
     * @param oldStringBuffer 需要转换的StringBuffer
     * @return 转换后的StringBuffer
     */
    private static StringBuffer humpConversionUnderscore(StringBuffer oldStringBuffer) {
        Pattern pattern = Pattern.compile("[A-Z]");
        Matcher matcher = pattern.matcher(oldStringBuffer);
        StringBuffer sb = new StringBuffer(oldStringBuffer);
        if (matcher.find()) {
            sb = new StringBuffer();
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
            matcher.appendTail(sb);
        } else {
            return sb;
        }
        return humpConversionUnderscore(sb);
    }

}
